<?php
namespace App\Admin\Controllers\Products;

use App\Admin\Extensions\Grid\Tool\Export;
use App\Models\Product\ProductMaterial;
use App\Models\Product\ProductMaterialApply;
use App\Util\RExcel;
use App\Util\User;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Grid;
use Encore\Admin\Widgets\Table;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Support\Facades\Request;

class MaterialReportOverdueController extends AdminController{

    protected $title = '材料报表(寻源超期率)';

    protected function grid(){

        $grid = new Grid(new ProductMaterialApply());
        $grid->model()
            ->selectRaw('*, count(`id`) as total')
            ->groupBy('apply_month')
            ->orderBy('apply_month', 'DESC');

        $grid->model()->collection(function (Collection $collection) {
            foreach($collection as $item) {
                $item->overdue_total = ProductMaterialApply::getOverdueSum($item->apply_month); //超期数量
                $item->overdue_ratio = round(intval($item->overdue_total) / intval($item->total), 2) ?? 0; //超期比例 = 超期数量 /申请总数
            }
            return $collection;
        });

        $grid->column('apply_month','申请月份')->expand(function ($model) {
            $headTitle = ['材料申请单号','申请材料名称','申请人','申请时间','寻源截止日期','寻源结果','寻源备注','寻源时间'];
            $applyValue = ProductMaterialApply::query()
                ->where('apply_month',$model->apply_month)
                ->whereColumn('origin_time', '>', 'cylce')
                ->get()
                ->map(function ($item) {
                    $res = [];
                    $res['apply_no'] = $item->apply_no;
                    $res['title'] = $item->title ?? '';
                    $res['admin_id'] = User::getUsernameById($item->admin_id) ?? '';
                    $res['created_at'] = $item->created_at ?? '';
                    $res['cylce'] = $item->cylce ? "<span style='color: red'>$item->cylce</span>" : '';
                    $res['origin_status'] = ProductMaterial::$_originStatus[$item->origin_status] ?? '';
                    $res['origin_remark'] = $item->origin_remark ?? '';
                    $res['origin_time'] = $item->origin_time ?? '';
                    return $res;
                })->toArray();
            return new Table($headTitle, $applyValue);
        });
        $grid->column('total','材料申请单总数')->help('当月材料申请单总数');
        $grid->column('overdue_total','超期单数')->help('材料超期的申请单数');
        $grid->column('overdue_ratio','超期率')->display(function ($value){
            return ($value && $value > 0) ? $value * 100 . '%' : 0;
        })->help('超期率 = 超期单数 / 申请单总量');

        $grid->paginate(10);
        $grid->disableExport();
        $grid->tools(function (Grid\Tools $tools){
            $tools->append(new Export('products/material-report-overdue-download'));
        });

        $grid->disableActions();
        $grid->disableBatchActions();
        $grid->disableCreateButton();
        $grid->filter(function($filter){
            $filter->column(1/2, function ($filter){
                $filter->equal('admin_id','申请人')->select(User::getCUserOptions());
                $filter->equal('audit_admin_id','审核人')->select(User::getCUserOptions());
            });
            $filter->column(1/2, function ($filter){
                $filter->equal('apply_month', '月份')->datetime(['format' => 'YYYY-MM']);
            });
        });

        return $grid;
    }

    public function download(){
        $request = Request::input();
        $query = $this->_initQuery($request);
        $this->_exeDownload($query);
    }

    private function _initQuery($filters){
        $query = ProductMaterialApply::query()->selectRaw('*, count(`id`) as total');
        foreach ($filters as $key => $_filter){
            if(in_array($key,['admin_id','audit_admin_id','apply_month'])){
                $query->whereIn($key,$_filter);
            }
        }
        $query->groupBy('apply_month');
        $query->orderBy('apply_month', 'DESC');
        return $query;
    }

    private function _exeDownload($query){
        $head = ['申请月份','材料申请单总数','超期单数','超期率 '];
        RExcel::exportCsv('材料单超期报表', function () use ($head, $query) {
            $fp = fopen('php://output', 'w');
            fwrite($fp, chr(0xEF).chr(0xBB).chr(0xBF));
            fputcsv($fp, $head);
            $query->chunk(1000, function ($re) use ($fp){
                $data = self::getDownloadData($re);
                foreach ($data as $item) {
                    fputcsv($fp, $item);
                }
            });
        });
    }

    public static function getDownloadData($res){

        foreach ($res as $model){
            $temp = [
                $model->apply_month ?? '',
                $model->total ?? 0,
                $model->overdue_total = ProductMaterialApply::getOverdueSum($model->apply_month), //超期数量
                $model->overdue_ratio = round(intval($model->overdue_total) / intval($model->total) * 100, 2) ?? 0, //超期比例 = 超期数量 /申请总数
            ];
            yield $temp;
        }
    }

}
